package com.rongji.egov.fileupload.s3.utils;

import com.rongji.egov.fileupload.RjFileProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.TimeZone;
@Service
public class S3FileIdUtils {
    @Resource
    private  RjFileProperties properties;

    /**
     * id的文件全路径
     * @param id id
     * @return path
     */
    public Path getFilePath(String id){
        long timestamp = getMilliseconds(id);
        LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), TimeZone
                .getDefault().toZoneId());

        //目录
        String path1 = File.separator + time.getYear() + File.separator + time.getMonthValue()
                + File.separator + time.getDayOfMonth() + File.separator + time.getHour();

        String targetFileName = id + "_" + getMD5(id);
        Path parent = Paths.get(properties.getPath(), path1);
        return Paths.get(parent.toString(), targetFileName);
    }

    /**
     * 得到时间戳
     * @param id idUtil产生的id
     * @return 时间戳
     */
    public static long getMilliseconds(String id){
        long result;
        try {
            result = getMillisecondsVersion2(id);
            return result;
        } catch (NumberFormatException e) {
            // 有错先都按之前的算法处理, 22年8月前是另一个算id的版本
            return getMillisecondsVersion1(id);
        }
    }


    public static long getMillisecondsVersion2(String uid) {
        long l = Long.parseLong(uid, 16);
        return (l >> 22) + 1288834974657L;
    }


    public static long getMillisecondsVersion1(String id){
        byte[] bytes = Base64.getUrlDecoder().decode(id);
        long result = 0;
        for (int i = 0; i < 4; i++) {
            result = (result << 8) + (bytes[i] & 0xFF);
        }
        return result * 1000;
    }


    public static String getMD5(String id){
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        md.update(id.getBytes());
        byte[] digest = md.digest();
        return DatatypeConverter.printHexBinary(digest).toUpperCase();
    }
}
